using Core.SimpleTemp.Application.UserApp;
using Core.SimpleTemp.Application.ZY;
using Core.SimpleTemp.Application.ZY.Dto;
using Core.SimpleTemp.Common;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Entitys;
using Core.SimpleTemp.Entitys.Sys;
using Core.SimpleTemp.Repositories;
using Core.SimpleTemp.Repositories.Internal;
using Core.Toolkit.Common;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Core.Toolkit.Core.Application;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Core.SimpleTemp.Application
{
    /// <summary>
    /// 许可证
    /// houts
    /// </summary>
    [AutoDi()]
    public class ZY_licenseService : BaseAppService<ZY_licenseDto, ZY_license, ZY_licenseRepository>
    {
        readonly ExcelHelp _excelHelp;
        readonly CoreDBContext _coreDbContext;
        readonly SysFileAppService _sysFileAppService;
        public ZY_licenseService(ZY_licenseRepository repository, ExcelHelp excelHelp, CoreDBContext coreDbContext, SysFileAppService sysFileAppService) : base(repository)
        {
            _excelHelp = excelHelp;
            _coreDbContext = coreDbContext;
            _sysFileAppService = sysFileAppService;
        }

        private LoadPageOffsetModelAuto<ZY_license, ZY_licenseDto> GetLoadPageOffsetMode(PagingModel<ZY_licenseDto> pagingQueryModel)
        {
            var loadPageOffsetModel = this.GetLoadPageOffsetModelAuto(pagingQueryModel);
            var baseQuery = _repository.QueryBase().AsNoTracking();
            loadPageOffsetModel.QueryWhere = this.CreateQRList()

            .Add("JobLicenseCode", "in") //编号
            .Add("JobLicenseUnit", "=") //作业单位
            .Add("JobManagerProple", "=") //作业负责人
            .Add("ApplicationTime", ">=", DateTimeFormat.getTime(pagingQueryModel.Model.ApplicationTime, "b"))
            .Add("ApplicationTime", "<", DateTimeFormat.getTime(pagingQueryModel.Model.ApplicationTimeEnd, "e"))
            .Add("EffectiveStartTime", ">=", DateTimeFormat.getTime(pagingQueryModel.Model.EffectiveStartTime, "b"))
            .Add("EffectiveStartTime", "<", DateTimeFormat.getTime(pagingQueryModel.Model.EffectiveStartTimeEnd, "e"));
            //审批页面不显示save状态票证
            if (PageTypeEnum.Approve.ToString() == pagingQueryModel.Model.PageType)
            {
                loadPageOffsetModel.QueryWhere.Add("JobLicenseState", "!=", TickeState.Save.ToString()); //
            }
            loadPageOffsetModel.BasqQuery = baseQuery;
            loadPageOffsetModel.Order = orderModel => orderModel.CreateTime;
            return loadPageOffsetModel;
        }


        public async Task<IPageModel<ZY_licenseDto>> GetList(PagingModel<ZY_licenseDto>
            pagingQueryModel)
        {
            var loadPageOffsetModel = GetLoadPageOffsetMode(pagingQueryModel);
            return await base.LoadPageOffsetAsync(loadPageOffsetModel);
        }


        public async Task<string> Export(PagingModel<ZY_licenseDto> pagingQueryModel)
        {
            var loadPageOffsetModel = GetLoadPageOffsetMode(pagingQueryModel);
            var DataList = await this.ExportDataAsync(loadPageOffsetModel);
            var excelData = DataList.Select(model => new
            {
                JobLicenseCode_title = "编号",
                model.JobLicenseCode,
                model.WorkRegion,
                WorkRegion_title = "工作区域",
                model.EffectiveStartTime,
                EffectiveStartTime_title = "有效开始时间",
                model.EffectiveEndTime,
                EffectiveEndTime_title = "有效结束时间",
                model.JobLocation,
                JobLocation_title = "作业地点",
                model.JobLicenseUnit,
                JobLicenseUnit_title = "作业单位",
                model.JobManagerProple,
                JobManagerProple_title = "作业负责人",
                model.PeopleWork,
                PeopleWork_title = "作业人",
                model.Guardian,
                Guardian_title = "监护人",
                model.WorkDescription,
                workDescription_title = "工作描述",
                model.IsJSA,
                isJSA_title = "是否jsa分析",
                model.IsImages,
                isImages_title = "是否附图片",
                model.ImagesDescription,
                imagesDescription_title = "图片描述",
                model.SecurityCardCode,
                SecurityCardCode_title = "安全交底卡和风险告知确定卡",
                model.SpecialEducationCode,
                SpecialEducationCode_title = "特种教育安全培训记录",
                model.JSACardCode,
                JSACardCode_title = "JSA卡",
                model.C_other,
                c_other_title = "危害意识其他",
                model.D_other,
                d_other_title = "个人安全防护其他",
                model.E_other,
                e_other_title = "工作前安全措施其他",
                model.F_other,
                f_other_title = "安全措施确认其他",
                model.JobLicenseState,
                JobLicenseState_title = "状态",
                model.CreateFactory,
                CreateFactory_title = "",
                model.CreateDept,
                CreateDept_title = "",
                model.UpdateDept,
                UpdateDept_title = "",
            }).ToList();




            return _excelHelp.Create(excelData);
        }


        public override async Task<ZY_licenseDto> InsertAsync(ZY_licenseDto dto, bool autoSave = true)
        {
            //添加 License信息
            var entity = await base.InsertAsync(dto, false);
            //添加关系表信息
            await AddContactDataAsync(entity.Id, dto);
            await _coreDbContext.SaveChangesAsync();
            return null;
        }

        public async Task<ZY_license> UpdateAsync(ZY_licenseDto dto)
        {
            //删除原字典
            var removeEntitys = _coreDbContext.ZY_Content.Where(a => a.PrimaryId == dto.Id);
            _coreDbContext.RemoveRange(removeEntitys);
            //删除原附件信息
            var removeFiles = _coreDbContext.SysFile.Where(a => a.B_ID == dto.Id);
            _coreDbContext.RemoveRange(removeFiles);

            var addFiles = AutoMapper.Mapper.Map<List<SysFile>>(dto.Attachment);
            addFiles.ForEach(a =>
            {
                a.B_ID = dto.Id;
                a.Id = Guid.Empty;
            });
            _coreDbContext.SysFile.AddRange(addFiles);

            //更新license信息
            await base.UpdateAsync(dto, false);
            //从新创建关系表信息
            await AddContactDataAsync(dto.Id, dto);
            await _coreDbContext.SaveChangesAsync();
            return null;
        }


        /// <summary>
        /// 单独处理关系表
        /// </summary>
        /// <param name="licenseId"></param>
        /// <param name="dto"></param>
        private async Task AddContactDataAsync(Guid licenseId, ZY_licenseDto dto)
        {
            //附件处理
            var fileIds = dto.Attachment.Select(a => a.Id);
            var files = _coreDbContext.SysFile.Where(a => fileIds.Contains(a.Id));
            foreach (var sysFile in files)
                sysFile.B_ID = licenseId;

            //工作类型选中
            var checkjobtype_b = dto.CheckJobType_B.Select(item => new ZY_Content
            {
                TableType = TicketTypeEnum.Workermit,
                TypeCoce = DicType.TypeB,
                PrimaryId = licenseId,
                ContentCode = item
            });
            _coreDbContext.ZY_Content.AddRange(checkjobtype_b);

            //危害意识选中
            var checkhazardidentification_c = dto.CheckHazardIdentification_C.Select(item => new ZY_Content
            {
                TableType = TicketTypeEnum.Workermit,
                TypeCoce = DicType.TypeC,
                PrimaryId = licenseId,
                ContentCode = item
            });
            _coreDbContext.ZY_Content.AddRange(checkhazardidentification_c);


            //危害意识选中
            var checkpersonalsecurityprotection_d = dto.CheckPersonalSecurityProtection_D.Select(item => new ZY_Content
            {
                TableType = TicketTypeEnum.Workermit,
                TypeCoce = DicType.TypeD,
                PrimaryId = licenseId,
                ContentCode = item
            });
            _coreDbContext.ZY_Content.AddRange(checkpersonalsecurityprotection_d);

            //工作前安全措施（工作区域准备）选中
            var checkpreworksafetymeasures_e = dto.CheckPreworkSafetyMeasures_E.Select(item => new ZY_Content
            {
                TableType = TicketTypeEnum.Workermit,
                TypeCoce = DicType.TypeE,
                PrimaryId = licenseId,
                ContentCode = item
            });
            _coreDbContext.ZY_Content.AddRange(checkpreworksafetymeasures_e);

            //安全措施确认
            var checkf_preworksafetymeasures_f = dto.CheckF_PreworkSafetyMeasures_F.Select(item => new ZY_Content
            {
                TableType = TicketTypeEnum.Workermit,
                TypeCoce = DicType.TypeF,
                PrimaryId = licenseId,
                ContentCode = item.Lable,
                ContentOptions = item.Value,
                ContentOptionsText = item.Text

            });

            _coreDbContext.ZY_Content.AddRange(checkf_preworksafetymeasures_f);


            //审批人
            var removeCheckSinga = _coreDbContext.ZY_CheckSignature.Where(a => a.PrimaryId == licenseId);
            _coreDbContext.ZY_CheckSignature.RemoveRange(removeCheckSinga);
            var checkSignature = dto.JobLicenceApproveList.Select(a => new ZY_CheckSignature()
            {
                PrimaryId = licenseId,
                TableType = TicketTypeEnum.Workermit,
                IsDutyOffice = a.IsDutyOffice,
                DutyId = a.Id
            });
            _coreDbContext.ZY_CheckSignature.AddRange(checkSignature);

            //确认人
            var removeConfirmSignature = _coreDbContext.ZY_ConfirmSignature.Where(a => a.PrimaryId == licenseId);
            _coreDbContext.ZY_ConfirmSignature.RemoveRange(removeConfirmSignature);
            var confirmSignature = dto.JobLicenceCheckList.Select(a => new ZY_ConfirmSignature()
            {
                PrimaryId = licenseId,
                TableType = TicketTypeEnum.Workermit.ToString(),
                SignatureDept = a.DepartmentId,
                SignatureUser = a.UserId
            });
            _coreDbContext.ZY_ConfirmSignature.AddRange(confirmSignature);


            if (dto.JobLicenseState == TickeState.Submit.ToString())
            {
                var jsaCode = dto.JSACardCode;
                var jsa = await _coreDbContext.ZY_JSA.SingleAsync(a => a.ApplicationNumber == jsaCode);
                if (jsa.BusinessId != null)
                    throw new CustomOperationException($"JSA {jsa.ApplicationNumber} 已关联其它票证，请先取消关联后在进行操作");
                jsa.BusinessId = licenseId;

                var securityCardCode = dto.SecurityCardCode;
                var safetyCard = await _coreDbContext.ZY_SafetyCard.SingleAsync(a => a.ConfirmationCardNumber == securityCardCode);
                if (safetyCard.BusinessId != null)
                    throw new CustomOperationException($"安全卡 {safetyCard.ConfirmationCardNumber} 已关联其它票证，请先取消关联后在进行操作");
                safetyCard.BusinessId = licenseId;


                var specialEducationCode = dto.SpecialEducationCode;
                var safetyEducation = await _coreDbContext.ZY_SafetyEducation.SingleAsync(a => a.RecordNumber == specialEducationCode);
                if (safetyEducation.BusinessId != null)
                    throw new CustomOperationException($"教育卡{safetyEducation.RecordNumber} 已关联其它票证，请先取消关联后在进行操作");
                safetyEducation.BusinessId = licenseId;
            }


        }
    }

}
